package com.sl.au.service.impl;


import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import com.sl.au.entity.Division;
import com.sl.au.entity.Hierarchy;
import com.sl.au.entity.Part;
import com.sl.au.repository.DivisionRepository;
import com.sl.au.repository.HierarchyRepository;
import com.sl.au.repository.PartRepository;
import com.sl.au.service.IdentifyService;

@Service("IdentifyService")
@Transactional
public class IdentifyServiceImpl extends BaseServiceImpl implements IdentifyService{
	
	@Resource
	private JdbcTemplate jdbcTemplate;
	
	@Autowired
	private HierarchyRepository hierarchyRepository;
	
	@Autowired
	private DivisionRepository divisionRepository;
	
	@Autowired
	private PartRepository partRepository;
	
	@Override
	public String getIdentifyByType(String id, String type, String table) {
		String Identify = "";
		String sql = "select getIdentifyByTableAndType(\""+table+"\",\""+ type +"\",\""+id+"\")";
		Identify = jdbcTemplate.queryForObject(sql, String.class);
		return Identify;
	}
	@Override
	public String getEventIdentifyByGridAndEventType(String areaId,String eventTypeId){
		
		String prefix ="";
		String postfix="";
		if (StringUtils.hasText(areaId)){
			prefix=this.getIdentifyByType(areaId, "eventShow", "division");
		}
		
		if (StringUtils.hasText(eventTypeId)){
			postfix=this.getIdentifyByType(eventTypeId, "eventShow", "eventType");
		}
		return prefix+postfix;
	}
	@Override
	public String getGirdIdentifyByAreaId(String oldIdentify,String areaId)
	{
		String prefix ="";
		String postfix="";
		
		if (StringUtils.hasText(areaId)){
			prefix=this.getIdentifyByType(areaId, "gridShow", "division");
			
			if(StringUtils.hasText(oldIdentify)&&oldIdentify.length()>=3){
				String areaIdentify=oldIdentify.substring(0, oldIdentify.length()-3);
				if(areaIdentify.equals(prefix)){
					return oldIdentify;
				}
			}
		}
		postfix=findGridOrder(areaId);
		
		return prefix+postfix;
	}
	private String findGridOrder(String areaId){
		String sql ="select MAX(gridIdentify) from sl_wcsi_gridarea where sl_wcsi_gridarea.areaId='"+areaId+"'";
		String identify = jdbcTemplate.queryForObject(sql, String.class);
	    int orderNum=1;
		if(StringUtils.hasText(identify)&&identify.length()>=3){
			orderNum=Integer.parseInt(identify.substring(identify.length()-3, identify.length()));
			if(orderNum<999){
				orderNum++;
				return getFormatStr(orderNum,100);
			}else{
				sql="select count(*) from sl_wcsi_gridarea where sl_wcsi_gridarea.areaId='"+areaId+"'";
				int count =Integer.parseInt(jdbcTemplate.queryForObject(sql, String.class));
				if(count==999){
					return null;
				}
				else{
					sql ="select gridIdentify from sl_wcsi_gridarea where sl_wcsi_gridarea.areaId='"+areaId+"' order by cast(gridIdentify as SIGNED INTEGER) ASC";
					List<Map<String, Object>> arrys = this.jdbcTemplate.queryForList(sql);
					int currentIdentify =0;
					for (Map<String, Object> arry : arrys) {
						if(StringUtils.hasText((String)arry.get("gridIdentify"))){
							String tempIdentify =(String)arry.get("gridIdentify");
							if(currentIdentify==Integer.parseInt(tempIdentify.substring(tempIdentify.length()-3, tempIdentify.length()))){
								currentIdentify++;
								continue;
							}else{
								if(currentIdentify==0){
									currentIdentify=Integer.parseInt(tempIdentify.substring(tempIdentify.length()-3, tempIdentify.length()));
									currentIdentify++;
									continue;
								}else
								{
									break;
								}
							}
						}
						else{
							continue;
						}
					}
					if(currentIdentify==0){
						return null;
					}else{
						return getFormatStr(currentIdentify,100);
					}
				}
			}
		}else{
			return getFormatStr(1,100);
		}
	}
	
	private String getFormatStr(int num,int formatLength){
		if(num<formatLength*10){
			if(num/formatLength>0){
				return Integer.toString(num);
			}
			else{
				String format="0";
				format+=getFormatStr(num,formatLength/10);
				return format;
			}
		}else{
			return getFormatStr(num%(formatLength*10),formatLength);
		}
	}
	
	@Override
	public int getPartBaseInfoOrderByPart(String id) {
		int orderNum = 0;
		String orderSql = " select ifnull(num,ct) as num from (select count(1) + 1 as ct from sl_wcsi_PartBaseInfo aa where aa.part_id = '"+id+"' ) ss left join "
				+ "( select num from ( select @num:=@num+1 as num, a.partOrderNum from sl_wcsi_PartBaseInfo a, (select @num:=0) t "
				+ " where a.part_id = '"+id+"' ORDER BY a.partOrderNum ) s where num <> partOrderNum ORDER BY num limit 1 ) tt on 1=1";
		orderNum = jdbcTemplate.queryForObject(orderSql, Integer.class);
		return orderNum;
	}
	
	@Override
	public int getPartBaseInfoOrderByHierarchy(String id) {
		int orderNum = 0;
		String orderSql = " select ifnull(num,ct) as num from (select count(1) + 1 as ct from sl_wcsi_PartBaseInfo aa where aa.hierarchy_id = '"+id+"' ) ss left join "
				+ "( select num from ( select @num:=@num+1 as num, a.orderNum from sl_wcsi_PartBaseInfo a, (select @num:=0) t "
				+ " where a.hierarchy_id = '"+id+"' ORDER BY a.orderNum ) s where num <> orderNum ORDER BY num limit 1 ) tt on 1=1";
		orderNum = jdbcTemplate.queryForObject(orderSql, Integer.class);
		return orderNum;
	}
	
	@Override
	public int getUserOrderByHierarchy(String id) {
		int orderNum = 0;
		String orderSql = " select ifnull(num,ct) as num from (select count(1) + 1 as ct from sl_au_user aa where aa.hierarchy = '"+id+"' ) ss left join "
				+ "( select num from ( select @num:=@num+1 as num, a.sOrderNum from sl_au_user a, (select @num:=0) t "
				+ " where a.hierarchy = '"+id+"' ORDER BY a.sOrderNum ) s where num <> sOrderNum ORDER BY num limit 1 ) tt on 1=1";
		orderNum = jdbcTemplate.queryForObject(orderSql, Integer.class);
		return orderNum;
	}
	
	@Override
	public void updateHierarchyIdentify(String hierarchyId) {
		//更新当前节点下的信息
		String newPartIdentify = this.getIdentifyByType(hierarchyId,"partShow","hierarchy");
		doUpdateHierarchyIdentify(newPartIdentify,hierarchyId);
		String newUserIdentify = this.getIdentifyByType(hierarchyId,"userShow","hierarchy");
		doUpdateUserIdentify(newUserIdentify,hierarchyId);
		//查询子节点
		List<Hierarchy> childNodes = hierarchyRepository.getHierarchysByGroupParent(hierarchyId);
		if(childNodes != null) {
			for(Hierarchy node : childNodes) {
				this.updateHierarchyIdentify(node.getId());
			}
		}
	}
	
	//执行更新
	public void doUpdateHierarchyIdentify(String newIdentify, String hierarchyId) {
		String orderSql = "UPDATE sl_wcsi_PartBaseInfo a SET a.hierarchyIdentify = CONCAT('"+newIdentify+"', SUBSTRING(a.hierarchyIdentify,-3)) WHERE a.hierarchy_id = '"+hierarchyId+"'";
		jdbcTemplate.update(orderSql);
	}

	//执行更新
	public void doUpdateUserIdentify(String newIdentify, String hierarchyId) {
		String orderSql = "UPDATE sl_au_user a SET a.sOrder = CONCAT('"+newIdentify+"', SUBSTRING(a.sOrder,-3)) WHERE a.hierarchy = '"+hierarchyId+"'";
		jdbcTemplate.update(orderSql);
	}
	
	@Override
	public void updateDivisionIdentify(String divisionId) {
		//更新当前节点下的信息
		String newGridIdentify = this.getIdentifyByType(divisionId,"gridShow","division");
		//更新网格中的区域编码
		doUpdateGridIdentify(newGridIdentify,divisionId);
		//更新部件所绑定的网格信息的区域编码
		doUpdatePartDivisionIdentify(newGridIdentify,divisionId);
		//查询子节点
		List<Division> childNodes = divisionRepository.getDivisionsByParent(divisionId);
		if(childNodes != null) {
			for(Division node : childNodes) {
				this.updateDivisionIdentify(node.getId());
			}
		}
	}
	
	//执行更新
	public void doUpdateGridIdentify(String newIdentify, String divisionId) {
		String orderSql = "UPDATE sl_wcsi_gridArea a SET a.gridIdentify = CONCAT('"+newIdentify+"', SUBSTRING(a.gridIdentify,-3)) WHERE a.areaId = '"+divisionId+"'";
		jdbcTemplate.update(orderSql);
	}
	
	//执行更新
	public void doUpdatePartDivisionIdentify(String newIdentify, String divisionId) {
		String orderSql = "UPDATE sl_wcsi_PartBaseInfo a SET a.divisionIdentify = '"+newIdentify+"' WHERE a.gridAreaInfo_id in (select b.id from sl_wcsi_gridArea b where b.areaId = '"+divisionId+"')";
		jdbcTemplate.update(orderSql);
	}
	
	@Override
	public void updatePartIdentify(String partId) {
		//更新当前节点下的信息
		String newPartIdentify = this.getIdentifyByType(partId,"partShow","part");
		doUpdatePartIdentify(newPartIdentify, partId);
		//查询子节点
		List<Part> childNodes = partRepository.getPartsByParent(partId);
		if(childNodes != null) {
			for(Part node : childNodes) {
				this.updatePartIdentify(node.getId());
			}
		}
	}
	
	//执行更新
	public void doUpdatePartIdentify(String newIdentify, String partId) {
		String orderSql = "UPDATE sl_wcsi_PartBaseInfo a SET a.partIdentify = CONCAT('"+newIdentify+"', SUBSTRING(a.partIdentify,-3)) WHERE a.part_id = '"+partId+"'";
		jdbcTemplate.update(orderSql);
	}
}
